﻿using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Data.SqlTypes;
using System.Linq;

using Kpmg.CompanyInfo;
using MySearch;


[ScriptService]
[WebService(Namespace = "http://aspnetajaxinaction.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ClientService : System.Web.Services.WebService
{
    private static readonly string ctxUserId = HttpContext.Current.User.Identity.Name.Substring(3);

    public ClientService()
    {

    }

    [WebMethod(EnableSession = true)]
    public string GetCurrentStaff()
    {
        Staff staff = StaffDAO.GetObjectByUserId(HttpContext.Current.User.Identity.Name.Substring(3));
        // Staff staff = StaffRepository.GetStaff();

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
        string response = jsSerializer.Serialize(staff);

        return response;
    }

    [WebMethod(EnableSession = true)]
    public string ListSatffs(string name)
    {
        IList<Staff> staffList = StaffDAO.ListObjectsByAjaxName(name).Distinct<Staff>(new Comparer()).ToList();

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
        string response = jsSerializer.Serialize(staffList);

        return response;
    }

    [WebMethod(EnableSession = true)]
    public string ListSatffsByRole(string name, string checkTeam, string roleId)
    {
        string team = String.Empty;
        if (checkTeam.ToLower() == "true")
            team = "1";
        else if (checkTeam.ToLower() == "false")
            team = "0";

        //IList<Staff> staffList = OAKStaffDAO.ListObjectsByAjaxName(name, team, roleId).Distinct<Staff>(new Comparer()).ToList();
        IList<Staff> staffList = new List<Staff>();

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
        string response = jsSerializer.Serialize(staffList);

        return response;
    }

    [WebMethod(EnableSession = true)]
    public string ListProfitCentre(string condition)
    {
        IList<Dept> CostCentreList = DeptDAO.ListObjectsByAjaxName(condition);

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
        string response = jsSerializer.Serialize(CostCentreList);

        return response;
    }

    [WebMethod(EnableSession = true)]
    public string ListInternalOrder(string orderOrdec, string profileCode)
    {
        Profile profile = ProfileOM.GetProfile(profileCode);

        if (profile == null)
            return "[]";
        IList<Chargeable> lstChargeable = profile.Chargeables.Where(x => x.ChargeableType == ChargeableType.InternalOrder).ToList();

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
        string response = jsSerializer.Serialize(lstChargeable);

        return response;
    }



    /*For dashboard*/
    /// <summary>
    /// Please note that the data should be returned by the context
    /// if team leader, then return corresponding data
    /// else, return empty
    /// </summary>
    /// <returns></returns>
    [WebMethod]
    public string GetDashboardsData()
    {
        // because the user role feature is not implemented at present,
        // therefore, use http.context directly
        string userID = HttpContext.Current.User.Identity.Name.Substring(3);

        // real: return TicketOM.GetDashboardData(userID);

        // dummy
        return "{ "
                + "\"baseDate\": \"201406090830\","
                + "\"yData\": [{"
                + "    Staff: \"Seamas\", jobs: [{ JobID:\"S001\", Desc: \"Sample1-1\", StartDate: \"201406091000\", EndDate: \"201406100900\", ActualHours:\"7\" },  "
                + "        { JobID:\"S002\", Desc: \"Sample1-2\", StartDate: \"201406101100\", EndDate: \"201406101700\", ActualHours:\"5\" },"
                + "        { JobID:\"S003\", Desc: \"Sample1-3\", StartDate: \"201406121000\", EndDate: \"201406121700\", ActualHours:\"6\" }  "
               + "     ]"
               + " },"
                + "        {"
                + "            Staff: \"Xiaobo\", jobs: [{ JobID:\"X001\", Desc: \"Sample2-1\", StartDate: \"201406100830\", EndDate: \"201406101730\", ActualHours:\"8\" }, "
                + "            { JobID:\"X002\", Desc: \"Sample2-2\", StartDate: \"201406110930\", EndDate: \"201406121200\", ActualHours:\"10.5\" }]"
               + "         },"
               + "         { Staff: \"Tomsen\", jobs: [{ JobID:\"T001\", Desc: \"Sample3-1\", StartDate: \"201406091530\", EndDate: \"201406161100\", ActualHours:\"28.5\" }] }] "
            + "}";
    }

    [WebMethod]
    public string UpdateDashboardsData(string json)
    {
        IDictionary<string, string> postedData = GetPostedData(json);

        // job, current job id
        // staff, current staff iid
        // movingHours, moved hours
        // prev: previous job id
        // next: next job id

        return GetDashboardsData();
    }

    private IDictionary<string, string> GetPostedData(string data)
    {
        IDictionary<string, string> dic = new Dictionary<string, string>();

        if (string.IsNullOrWhiteSpace(data))
            return dic;
        string[] arr = data.Split(',');

        foreach (string str in arr)
        {
            string[] kv = str.Split('|');

            if (dic.Keys.Contains(kv[0]))
                continue;

            if (kv.Length != 2)
                continue;

            dic.Add(kv[0], kv[1]);
        }

        return dic;
    }

}

public class SqlDateTimeConverter : JavaScriptConverter
{

    public override IEnumerable<Type> SupportedTypes
    {
        //Define the ListItemCollection as a supported type.
        get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(SqlDateTime) })); }
    }


    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        SqlDateTime objSqlDateTime = (SqlDateTime)obj;

        if (!objSqlDateTime.IsNull)
        {
            Dictionary<string, object> listDict = new Dictionary<string, object>();
            listDict.Add("val", objSqlDateTime.Value.ToString("yyyy-MM-dd hh:mm:ss"));

            return listDict;
        }
        return new Dictionary<string, object>();
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        return null;
    }
}

public class Comparer : IEqualityComparer<Staff>
{
    public bool Equals(Staff x, Staff y)
    {
        if (x == null)
            return y == null;
        return x.StaffNo == y.StaffNo;
    }

    public int GetHashCode(Staff obj)
    {
        if (obj == null)
            return 0;
        return obj.UserID.GetHashCode();
    }
}
